package com.rachel.commonsdk.custom.bannerview;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import java.util.List;

/**
 * Created by zhengshaorui on 2017/8/16.
 */

public class BannerViewPager extends ViewPager {
    private static final String TAG = "BannerViewPager";
    private BannerCustomAdapter mBannerCustomAdapter;

    public BannerViewPager(Context context) {
        super(context);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setAdapter(List<View> views) {
        setAdapter(new BannerViewAdapter(views));
    }



    class BannerViewAdapter extends PagerAdapter{
        List<View> views;
        public BannerViewAdapter(List<View> views) {
           this.views = views;
        }


        @Override
        public int getCount() {
            //设置一个很大的数，用来实现轮播效果
             return this.views.size() * 400;

        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //自己适配类型，比如imageview
            View view = null;
            if (this.views != null){
                //对Viewpager页号求模去除View列表中要显示的项
                position %= this.views.size();


                //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
                view = this.views.get(position);
                ViewParent viewParent = view.getParent();
                if (viewParent!=null){
                    ViewGroup parent = (ViewGroup)viewParent;

                    parent.removeView(view);
                }
            }
           // view = this.views.get(position % this.views.size());
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
          //上面已经对 item remove了，这里如果再次remove，则实现不出来
             container.removeView((View) object);
        }
    }


}
